package com.yxkj.syh.app.huarong.activities.msg;

import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.syh.app.basic.base.BaseActivity;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.adps.MsgListAdp;
import com.yxkj.syh.app.huarong.bean.PagesRequest;
import com.yxkj.syh.app.huarong.databinding.ActivityMsgListBinding;

public class MsgListActivity extends BaseActivity<ActivityMsgListBinding, MsgListVM> {
    private PagesRequest request;
    private MsgListAdp mMsgListAdp;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_msg_list;
    }

    @Override
    protected int getViewModelId() {
        return BR.msgListVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mMsgListAdp = new MsgListAdp();
        mVDBinding.rvMsg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mMsgListAdp.bindToRecycleView(mVDBinding.rvMsg);

        mVDBinding.srlMsg.setOnRefreshListener(refreshLayout -> {
            initData();
        });
        mVDBinding.srlMsg.setOnLoadMoreListener(refreshLayout -> {
            request.setPageIndex(request.getPageIndex() + 1);
            mViewModel.msgList(request);
        });
        mVDBinding.srlMsg.setEnableLoadMore(false);

        mVDBinding.titleView.setLeftOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        request = new PagesRequest();
        request.setPageIndex(1);
        request.setPageSize(10);

        mViewModel.msgList(request);
    }


    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldMsgPreviews.observe(this, data -> {
            if (mVDBinding.srlMsg.isRefreshing()) {
                mVDBinding.srlMsg.finishRefresh();
            }
            if (mVDBinding.srlMsg.isLoading()) {
                mVDBinding.srlMsg.finishLoadMore();
            }

            if (request.getPageIndex() == 1) {
                mMsgListAdp.setNewData(data.getRecords());
            } else {
                mMsgListAdp.addAll(data.getRecords());
            }

            if (request.getPageIndex() < data.getPages()) {
                mVDBinding.srlMsg.setEnableLoadMore(true);
            } else {
                mVDBinding.srlMsg.setEnableLoadMore(false);
            }
        });
    }
}
